from pynput.keyboard import Key, Controller
import time
import pygetwindow as gw

# 创建键盘控制器实例
keyboard = Controller()

# 检查当前活动窗口标题是否包含 "原神"（不区分大小写）


def is_yuanshen_window_active():
    try:
        active_window = gw.getActiveWindow()
        if active_window is None:
            return False
        window_title = active_window.title
        return "原神" in window_title
    except:
        return False


def focus_window(title_keyword):
    """
    激活包含关键词的窗口
    :param title_keyword: 窗口标题中的关键词，如 "Chrome", "微信"
    """
    try:
        # 查找所有匹配的窗口（不区分大小写）
        windows = gw.getWindowsWithTitle(title_keyword)
        if not windows:
            print(f"❌ 未找到包含 '{title_keyword}' 的窗口")
            return False

        # 通常取第一个匹配的窗口
        window = windows[0]
        print(f"🎯 找到窗口: {window.title}")

        # 如果最小化，先恢复
        if window.isMinimized:
            window.restore()
            time.sleep(0.5)

        # 将窗口带到前台
        window.activate()  # 或使用 window.restore() + win32gui.SetForegroundWindow()
        print(f"✅ 已切换到: {window.title}")
        return True

    except Exception as e:
        print(f"❌ 切换失败: {e}")
        return False


focus_window("原神")
time.sleep(1)

# BPM 和速度计算
bpm = 96
speed = round(60 / bpm, 2)

# 乐谱
str_array1 = ["#|3|1", "#|3|0.5", "#|5|0.5", "#|6|0.5", "+|1|0.5", "+|1|0.5", "#|6|0.5",
              "#|5|1", "#|5|0.5", "#|6|0.5", "#|5|2"]

str_array2 = ["#|3|1", "#|3|0.5", "#|5|0.5", "#|6|0.5", "+|1|0.5", "+|1|0.5", "#|6|0.5",
              "#|5|1", "#|5|0.5", "#|6|0.5", "#|5|2"]

str_array3 = ["#|5|1", "#|5|1", "#|5|1", "#|3|0.5", "#|5|0.5", "#|6|1", "#|6|1",
              "#|5|2"]

str_array4 = ["#|3|1", "#|2|0.5", "#|3|0.5", "#|5|1", "#|3|0.5", "#|2|0.5", "#|1|1",
              "#|1|0.5", "#|2|0.5", "#|1|2"]

str_array5 = ["#|3|0.5", "#|2|0.5", "#|1|0.5", "#|3|0.5", "#|2|1.5", "#|3|0.5", "#|5|1",
              "#|6|0.5", "+|1|0.5", "#|5|2"]

str_array6 = ["#|2|1", "#|3|0.5", "#|5|0.5", "#|2|0.5", "#|3|0.5", "#|1|0.5", "-|6|0.5",
              "-|5|2"]

str_array7 = ["-|6|1", "#|1|1", "#|2|1.5", "#|3|0.5",
              "#|1|0.5", "#|2|0.5", "#|1|0.5", "-|6|0.5", "-|5|2"]

# 动态合并
arrays = [globals()[f"str_array{i}"]
          for i in range(1, 8)]  # range(1,20)即1-19
all_items = [item for arr in arrays for item in arr]

# 键盘映射
str_scale1 = ["a", "s", "d", "f", "g", "h", "j"]
str_scale2 = ["q", "w", "e", "r", "t", "y", "u"]
str_scale3 = ["z", "x", "c", "v", "b", "n", "m"]

# 遍历播放音符
for item in all_items:
    # 实时检查窗口是否仍然是 yuanshen
    if not is_yuanshen_window_active():
        print("警告：当前活动窗口已切换出 '原神'，程序终止。")
        break

    parts = item.split("|")
    key_char = ""
    duration = speed * float(parts[2])

    # 解析音符
    if parts[0] == "#":
        if parts[1] == "0":
            key_char = "0"
        else:
            key_char = str_scale1[int(parts[1]) - 1]
    elif parts[0] == "+":
        key_char = str_scale2[int(parts[1]) - 1]
    elif parts[0] == "-":
        key_char = str_scale3[int(parts[1]) - 1]

    # 模拟按键
    if key_char == "0":
        time.sleep(duration)
    else:
        keyboard.press(key_char)
        if duration >= speed * 0.75:
            time.sleep(duration)
            keyboard.release(key_char)
            time.sleep(0.05)
        else:
            time.sleep(0.03)
            keyboard.release(key_char)
            time.sleep(duration - 0.03)  # 补齐剩余时间
